package com.lingzerg.mainacct.DAO.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.lingzerg.mainacct.DAO.UserDao;
import com.lingzerg.mainacct.entity.User;
import com.lingzerg.tool.HibernateUtil;

public class UserDaoImpl implements UserDao {

	public boolean checkLogin(String username, String password) {
		System.out.println("checkLogin");
		User user = findByUsername(username);
		return user == null ? false : user.getPassword().equals(password);
	}
	
	@SuppressWarnings("unchecked")
	public User findByUsername(String username) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("from User where username=?").setParameter(0, username);
		List<User> list = query.list();
		session.getTransaction().commit();
		if(list!=null && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	
	public User get(long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		return (User) session.get(User.class, id);
	}

	

	public User save(User user) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(user);
		session.getTransaction().commit();
		return user;
	}

}
